package com.ztrue.common.utilities;

import java.util.Collection;
import java.util.Date;

/**
 * Created by zhangw on 2016/4/5.
 * 字符串工具
 */
public class StringUtil {
    /**
     * 将对象转为默认字符串格式
     *
     * @param object 转换对象
     * @return
     */
    public static String toString(Object object) {
        if (object == null) {
            return null;
        }
        String str = null;
        if (object instanceof Date) {
            str = DateUtil.toString((Date) object, "yyyy-MM-dd");
        } else {
            str = object.toString();
        }
        return str;
    }

    /**
     * 向左填充内容
     *
     * @param i      原始数据
     * @param length 填充后的长度
     * @param str    填充内容
     * @return
     */
    public static String toLeftFilled(Integer i, int length, String str) {
        String s = i.toString();
        int diff = length - s.length();
        if (diff > 0) {
            for (int j = 0; j < diff; j++) {
                s = str + s;
            }
        }
        return s;
    }

    /**
     * 是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.trim().length() == 0;
    }

    /**
     * 是否不为空
     *
     * @param s
     * @return
     */
    public static boolean isNotEmpty(String s) {
        return s != null && s.trim().length() > 0;
    }

    /**
     * 判断字符串是否数字
     *
     * @param s
     * @return
     */
    public static boolean isLong(String s) {
        if (s.length() > 20) {
            return false;
        }
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*");
        java.util.regex.Matcher match = pattern.matcher(s);
        if (match.matches()) {
            try {
                Long.parseLong(s);
                return true;
            } catch (Exception ex) {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 判断字符串是否数字
     *
     * @param s
     * @return
     */
    public static boolean isInteger(String s) {
        if (s.length() > 11) {
            return false;
        }
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*");
        java.util.regex.Matcher match = pattern.matcher(s);
        if (match.matches()) {
            try {
                Integer.parseInt(s);
                return true;
            } catch (Exception ex) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static String[] toStringArray(Collection<String> collection) {
        if (collection == null) {
            return null;
        }
        return collection.toArray(new String[collection.size()]);
    }
}
